<template>
  <div>
    <el-container>
      <el-main style="margin-left:-12px;font-weight: bolder;">{{id? '编辑文章':'新建文章'}}</el-main>
    </el-container>

    <!-- native指向原生表单  -->
    <el-form label-width="80px" @submit.native.prevent="save">
      <el-form-item label="所属分类">
        <el-select error required multiple  v-model="model.categories" placeholder="name">
          <el-option v-for=" item in categories" :key="item._id" :label="item.name" :value="item._id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题">
        <el-input  prefix-icon="el-icon-edit-outline"  clearable maxlength = "100"  error required v-model="model.title" placeholder="name"></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <!--富文本编辑器 -->
        <!-- <vue-editor useCustomImageHandler @imageAdded = "handleImageAdded" v-model="model.body"> -->
        <vue-editor v-model="model.body">
        </vue-editor>
        
      </el-form-item>
      <el-form-item>
        <el-button class="el-button--medium el-button--medium-ArticleEdit"  type="primary" native-type="submit" :plain="true">保存</el-button>
        <el-button type="danger" size="medium" native-type="button" @click="cancel" v-show="this.id" :plain="true">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { VueEditor} from 'vue2-editor'

export default {
  props: {
    id: {}
  },
  data() {
    return {
      model: {},
      categories: []
    };
  },
  created() {
    this.fetchCategories();
    this.id && this.fetch();
  },
  methods: {
    async save() {
      //实现新增的保存和编辑的保存
      if (this.id) {
        const response = await this.$http.put(`rest/articles/${this.id}`,this.model);
      } else {
        const response = await this.$http.post("rest/articles", this.model);
      }
      this.$router.push("/articles/list");
      
      this.$message({
        type: "success",
        message: "保存成功",
        duration: 2000
      });
    },
    async fetch() {
      const response = await this.$http.get(`rest/articles/${this.id}`);
      this.model = response.data;
    },
    async fetchCategories() {
      const response = await this.$http.get(`rest/categories`);
      this.categories = response.data;
    },
    // 富文本编辑器图片处理
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
     
      let formData = new FormData();
      formData.append("file", file);

      let response = await this.$http.post('upload', formData)
      Editor.insertEmbed(cursorLocation, "image", response.data.url);
      resetUploader();
    },
     //取消保存返回上一页
    cancel() {
      this.$router.go(-1);
    }
  },
  components:{
    VueEditor
  }
};
</script>

<style>
.el-button--medium-ArticleEdit{
    padding: 15px 60px!important;
}
/* 富文本编辑器 */
.ql-snow .ql-picker-label::before {
  top: -7px;
  position: relative;
}
</style>